http_request = require('./util').http_request
resErr = require("./util").resErr
async = require "async"
util = require "util"

make_call_task = (r,i,req,result) ->
  
  [uri, params, method] = r

  if typeof(method) == "string"
    method = method.toUpperCase()
  else
    method = "GET"

  if params in [null,undefined]
    params = {}

  (task_cb) ->
    http_request method,uri,params, (err,data) ->
      if err
        result[i] = {error:err}
        return task_cb "Error:#{uri}:#{JSON.stringify params}:#{err}"
      else
        result[i] = data
        return task_cb null
    , {Cookie: ("#{k}=#{v}" for own k,v of req.cookies).join(';')}
  
exports.combine_call = (req,res) ->

  call = req.param("call")

  unless call and util.isArray(call)
    return resErr res, "没有类型为数组的必选参数: call"
  
  result = (null for x in call)

  for r in call

    [uri, params, method] = r

    if typeof(method) == "string"
      method = method.toUpperCase()
    else
      method = "GET"

    if params in  [null,undefined]
      params = {}
      
    unless typeof(uri) == "string"
      return resErr res, "参数类型错误,uri 应该是string:#{uri}"

    if uri[0] == '/'
      uri = r[0] = "#{req.protocol}://#{req.host}#{uri}"
    unless /[^\.]*.gf.com.cn/.exec(uri)
      return resErr res, "仅支持广发证券的接口调用: #{uri}"
    unless typeof(params) == "object"
      return resErr res, "参数类型错误,params 应该是object:#{uri}"
    unless method in ["GET","POST"]
      return resErr res, "method 错误: #{method}"

  tasks = (make_call_task(r,i,req,result) for r,i in call)
                
  async.parallel tasks, (err) ->
    if err
      return resErr res, err
    else
      res.json result
      

            
            
    
  
